package com.roshan.web.security.util;

import org.apache.log4j.Logger;

import com.roshan.web.util.constants.LoggerWebMessages;
import com.thoughtworks.xstream.XStream;

public class CommonUtils {

    private static final Logger logger = Logger.getLogger(CommonUtils.class);

    public static byte[] toBytes(Object object) {
        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
        try {
            java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos);
            oos.writeObject(object);
        } catch (java.io.IOException ioe) {

            logger.error(LoggerWebMessages.COULD_NOT_CONVERT_OBJECT_TO_BYTE_ARRAY);
            logger.error(ioe.getMessage(), ioe);
        }
        return baos.toByteArray();
    }

    public static Object toObject(String xmlString) {
        XStream xStream = new XStream();
        return xStream.fromXML(xmlString);
    }

    public static Object toObject(byte[] bytes) {
        Object object = null;
        try {
            object = new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(bytes)).readObject();
        } catch (java.io.IOException ioe) {
            logger.error(LoggerWebMessages.COULD_NOT_CONVERT_OBJECT_TO_BYTE_ARRAY);
            logger.error(ioe.getMessage(), ioe);
        } catch (java.lang.ClassNotFoundException cnfe) {
            logger.error(LoggerWebMessages.COULD_NOT_CONVERT_OBJECT_TO_BYTE_ARRAY);
            logger.error(cnfe.getMessage(), cnfe);
        }
        return object;
    }

    public static String toXmlString(Object object) {
        XStream xStream = new XStream();
        return xStream.toXML(object);
    }

}
